/**
 * 设置语言，使用vue3，加载json文件的方式加载语言
 */
import {
	defineStore
} from 'pinia';
import {
	ref
} from 'vue';
import DamStore from "@/dam_common/respository/data/dam_store";
import ObjectUtil from "@/dam_common/utils/ObjectUtil"
import LangDatas from "@/static/i18n/strings.json"

const StoreKey = "lang";

const useLangStore = defineStore(StoreKey, () => {
	const langName = ref(''); //当前语言
	const langData = ref([]); //语言数据
	const setLangName = (_langName) => {
		langName.value = _langName;
	};
	const setLangData = (_langData) => {
		langData.value = _langData;
	};
	const getLangName = () => {
		return langName.value;
	};
	const getLangData = () => {
		return langData.value;
	};
	return {
		langName,
		langData,
		setLangName,
		setLangData,
		getLangName,
		getLangData,
	}
});

/**
 * 初始化语言
 * @param {Boolean} useLocal 是否使用系统语言 
 */
function initLang(useLocal) {
	let langJson = LangDatas;
	let value = DamStore.get(StoreKey);
	let lang = "zh-Hans";
	if (useLocal) {
		const language = uni.getLocale();
		lang = language;
	} else {
		if (value && value !== '') {
			lang = value;
		}
	}
	changeLangWithData(lang, langJson);
}

/**
 * 获取当前的语言
 */
function getCurrentLangName() {
	let langStore = useLangStore();
	return langStore.getLangName();
}

/**
 * 获取当前的语言
 */
function getCurrentLangData() {
	let langStore = useLangStore();
	return langStore.getLangData();
}

/**
 * 改变语言
 * @param {String} lang
 */
function changeLang(lang) {
	return changeLangWithData(lang, LangDatas);
}
/**
 * 改变语言
 * @param {String} lang		
 * @param langJson 语言json
 */
function changeLangWithData(lang, langJson = []) {
	let langStore = useLangStore();
	let _langJson = langJson
	if (!langJson) {
		_langJson = LangDatas;
		return;
	}
	langStore.setLangName(lang);
	langStore.setLangData(_langJson[lang]);
	return DamStore.save(StoreKey, lang)
}
export default {
	useLangStore,
	initLang,
	getCurrentLangName,
	getCurrentLangData,
	changeLang
}